using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ToastMgr : MonoBehaviour
{
    private static ToastMgr instance;
    public static ToastMgr Instance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<ToastMgr>();
                if (instance == null)
                {
                    GameObject go = new GameObject("LaMianMgr");
                    instance = go.AddComponent<ToastMgr>();
                }
            }
            return instance;
        }
    }

    private Queue<string> toastContentQueue = new Queue<string>();
    private Queue<GameObject> toastGoQueue = new Queue<GameObject>();

    private void Update()
    {
        if (toastContentQueue.Count <= 0) return;

        GameObject toastGo = Instantiate(Resources.Load<GameObject>("Prefabs/ToastGO"), GameObject.Find("UIRoot").transform);
        toastGoQueue.Enqueue(toastGo);

        toastGo.transform.Find("Text").GetComponent<Text>().text = toastContentQueue.Dequeue();

        (toastGo.transform as RectTransform).position = new Vector3(Screen.width / 2f, Screen.height / 2f, 0f);

        Invoke("DestoryToast", 2);
    }


    public void Toast(string content)
    {
        toastContentQueue.Enqueue(content);
    }


    public void DestoryToast()
    {
        GameObject toastGo = toastGoQueue.Dequeue();

        StartCoroutine(ToastMove(toastGo));
    }

    public IEnumerator ToastMove(GameObject toastGo)
    {
        while (toastGo.transform.position.y < Screen.height)
        {
            toastGo.transform.position = 
                Vector3.Lerp(toastGo.transform.position, toastGo.transform.position + new Vector3(toastGo.transform.position.x, Screen.height, toastGo.transform.position.z), 0.01f);
            yield return null;
        }

        Destroy(toastGo);
        yield break;
    }
}
